import { useEffect, useMemo, useState } from 'react'
import PropTypes from 'prop-types'
import { UsergroupAddOutlined } from '@ant-design/icons'
import InputSelect from './InputSelect'
import {
  queryWorkFlowGroups,
  queryModelerGroups,
  queryList as queryIdmGroups,
} from '../../apis/group'
import { message } from 'antd'

const apis = {
  workflow: queryWorkFlowGroups,
  modeler: queryModelerGroups,
  idm: queryIdmGroups
}

const InputUserGroup = ({
  multiple,
  saveType,
  usePosition = 'workflow',
  ...props
}) => {

  const [userGroups, setUserGroups] = useState([])

  useEffect(() => {
    queryOptions()
  }, [])

  const queryOptions = async () => {
    try {
      const data = await apis[usePosition]()
      if(usePosition === 'idm'){
        setUserGroups(data)
      }else{
        setUserGroups(data.data)
      }
    } catch (error) {
      message.error('查询用户组失败')
    }
  }

  const options = useMemo(() => {
    return userGroups.map(el => ({
      value: el.id,
      label: el.name
    }))
  }, [userGroups])

  const getValue = () => {
    const { value } = props
    if (saveType && saveType === 'all') {
      if (multiple) {
        return value ? value.map(el => el.id) : undefined
      } else {
        return value ? value.id : undefined
      }
    } else {
      if (multiple) {
        return value ? value.split(',') : []
      } else {
        return value
      }
    }
  }

  const handleChange = (value) => {
    const { onChange } = props
    if (saveType && saveType === 'all') {
      let newValue
      if (multiple) {
        newValue = value.map(el => userGroups.find(group => group.id === el))
        onChange(newValue)
      } else {
        newValue = userGroups.find(group => group.id === value)
        onChange(newValue)
      }
    } else {
      if (multiple) {
        onChange(value.join(','))
      } else {
        onChange(value)
      }
    }
  }

  return <InputSelect
    showSearch
    suffixIcon={<UsergroupAddOutlined />}
    autoComplete="off"
    placeholder="请选择用户组"
    {...props}
    options={options}
    multiple={multiple}
    value={getValue()}
    onChange={handleChange}
  ></InputSelect>
}

InputUserGroup.propTypes = {
  multiple: PropTypes.bool,
  usePosition: PropTypes.oneOf(['idm', 'workflow', 'modeler']),
  saveType: PropTypes.oneOf(['id', 'all'])
}

InputUserGroup.propsMap = [
  {
    type: 'boolean',
    name: 'multiple',
    label: '是否多选'
  },
  {
    type: 'select',
    name: 'usePosition',
    label: '使用场景',
    inputProps: {
      options: [
        { value: 'idm', label: '用户管理' },
        { value: 'workflow', label: '工作流' },
        { value: 'modeler', label: '系统设计' },
      ]
    }
  },
  {
    type: 'select',
    name: 'saveType',
    label: '保存形式',
    inputProps: {
      options: [
        { value: 'id', label: '仅ID' },
        { value: 'all', label: '整行数据' }
      ]
    }
  }
]

export default InputUserGroup